<template>
	<view class="Home">
		<view class="introduce">
			<image class="backs" src="@/static/imgs/backs.png" mode=""></image>
			<view class="content poa top-left">
				<image class="logo" src="@/static/imgs/gs.png" mode=""></image>
				<view class="title color">快捷外呼系统</view>
				<view class="deacs color">努力是业绩的燃料，拼搏让成果更耀眼</view>
			</view>
		</view>
		<view class="information">
			<view class="person">
				<image class="person-img" src="@/static/imgs/grzx.png" mode=""></image>
				<view class="infos">
					<view class="sub size-34">{{userInfo.nickname || '-'}}</view>
					<view class="desc sub size-28">{{userInfo.phone}}</view>
				</view>
				<view class="selected size-30 poa" :class="{'selecteds':!dialingBool}">
					<view class="drop backs"></view>
					{{dialingBool ? '已开启' : '已关闭'}}
				</view>
			</view>
			<view class="calling">
				<view class="outbound">
					<image class="outbound-icons" src="@/static/icon/zfj.png" mode=""></image>
				</view>
				<view class="characters">
					<view class="switch">
						<text class="sub size-36">开启新客自动外呼</text>
						<button class="switch-button dis size-30 background"
							@click="onAutomatic">{{!dialingBool ? '开启' : '关闭'}}</button>
						<!-- 	<up-switch inactiveColor="#ccc" :size="23" v-model="dialingBool"
							@change="onAutomatic"></up-switch> -->
					</view>
					<view class="cribe sub size-28">当开启时系统一旦接收到新分配的客户信息，将立即自动跳转手机拨打界面，实现无缝对接</view>
				</view>
			</view>
			<view class="steps backgroundf">
				<view class="text-align">
					<view class="step size-30 colorf background dis">1</view>
					<view class="size-24 sub">启动外呼</view>
				</view>
				<view class="strip"></view>
				<view class="text-align">
					<view class="step size-30 colorf background dis">2</view>
					<view class="size-24 sub">收到新用户</view>
				</view>
				<view class="strip"></view>
				<view class="text-align">
					<view class="step size-30 colorf background dis">3</view>
					<view class="size-24 sub">跳转拨号</view>
				</view>
			</view>
			<view class="explanation size-28 sub">
				<view class="size-30">规则说明</view>
				<view>1.开启自动外呼时，接到新客户会自动跳转至手机拨号</view>
				<view>2.手动拨打功能不受自动外呼开关影响，始终可用</view>
				<view>4.接到多条新客服时会按照进入顺序跳转拨打页面，直到所有新客户全部跳转为止</view>
				<view>5.使用外呼功能期间，需停留在当前页面</view>
			</view>
			<view class="log-out" @click="onLogOut">
				<up-button text="退出登录"></up-button>
				<view class="inset-bottom"></view>
			</view>
		</view>
	</view>
</template>

<script setup>
	import { ref, onMounted, onBeforeUnmount } from 'vue'
	import { onShow, onLoad, onHide } from '@dcloudio/uni-app';
	import { Clear, GetInfo, SaveOpenNewClientCall } from '@/http/api/index.js'
	import { useWebSocket } from '@/utils/websocket.js'
	const { connect, send, onMessage, close } = useWebSocket()
	const dialingBool = ref(true);
	const userInfo = ref('');
	// const messages = ref('')
	const inputMessage = ref('')
	onLoad(async () => {
		// console.log('checkCallPermission', await checkCallPermission())
		// dialingBool.value = uni.getStorageSync('dialing') || true
		// userInfo.value = uni.getStorageSync('userInfo')
		asyncGetInfo()
	})
	// 初始化 WebSocket
	onShow(async () => {
		if (uni.getStorageSync('dialing')) onMessages()
		// setTimeout(() => {
		// 	handleSend()
		// }, 30000)
	})
	onHide(() => {
		close()
		uni.setStorageSync('dialing', true)
		console.log('页面移除时')
	})

	// 获取业务员信息
	const asyncGetInfo = async () => {
		const { data } = await GetInfo()
		userInfo.value = data
		dialingBool.value = data.open_new_client_call
	}
	// 开启/关闭新客外呼
	const asyncSaveOpenNew = async () => {
		const { data } = await SaveOpenNewClientCall()
		console.log('data.open_new_client_call', data)
		asyncGetInfo()
	}
	const onMessages = async () => {
		try {
			await connect('wss://call.deep123.vip/api/v1/dial/getData?code=1')
			onMessage((data) => {
				if (data && data.type != 'pong') {
					if (uni.getStorageSync('dialing')) uni.removeStorageSync('dialing')
					console.log('datadatadatadatadatadatadatadatadata', data)
					if (data) asyncClear(data) // 清除拨号
					autoCall(data) // 拨号
				}
				// messages.value.push(data) // 接收消息并更新响应式数据
				console.log('连接成功 接收消息并更新响应式数据', data)
			})
		} catch (err) {
			console.log('连接失败', err)
			uni.showToast({ title: '连接失败', icon: 'none' })
		}
	}
	const asyncClear = async (phone) => {
		console.log('phone', phone)
		try {
			const { data } = await Clear({ phone: JSON.stringify(phone) })
			console.log('data', data)
		} catch (err) {
			console.log('请求失败', err)
		}
	}
	// 自动拨打
	const autoCall = (phoneNumber) => {
		// 安卓平台判断
		if (uni.getSystemInfoSync().platform === 'android') {
			const main = plus.android.runtimeMainActivity();
			const Intent = plus.android.importClass('android.content.Intent');
			const Uri = plus.android.importClass('android.net.Uri');

			// 创建拨号Intent
			const intent = new Intent(Intent.ACTION_CALL);
			intent.setData(Uri.parse('tel:' + phoneNumber));

			// 动态申请权限
			const permission = 'android.permission.CALL_PHONE';
			main.requestPermissions([permission], 0);

			// 执行拨号（需处理权限回调）
			main.startActivity(intent);
		} else {
			uni.showToast({ title: '仅支持安卓平台' });
		}
	};
	// 发送消息
	// const handleSend = () => {
	// 	// if (!inputMessage.value.trim()) return
	// 	send(1)
	// 	// inputMessage.value = 
	// }
	const onLogOut = () => {
		uni.showModal({
			title: '温馨提示',
			content: '确认退出登录吗？',
			success: function(res) {
				if (res.confirm) {
					close()
					uni.showToast({
						title: '退出中',
						duration: 2000,
						mask: true,
						icon: 'loading'
					});
					setTimeout(() => {
						uni.removeStorageSync('token')
						uni.removeStorageSync('userInfo')
						uni.reLaunch({
							url: '/packageNotes/logon/index'
						});
					}, 2000)
				} else if (res.cancel) {
					console.log('用户点击取消');
				}
			}
		});
	}
	const onAutomatic = (evet) => {
		console.log('dialingBool.value', dialingBool.value)
		if (dialingBool.value) {
			uni.showModal({
				title: '温馨提示',
				content: '关闭后只能通过后台手动点击拨号，确认关闭吗？',
				success: function(res) {
					if (res.confirm) {
						console.log('用户点击确定');
						asyncSaveOpenNew()
						// uni.setStorageSync('dialing', false)
						// dialingBool.value = false
					} else if (res.cancel) {
						// uni.setStorageSync('dialing', true)
						// dialingBool.value = true
						console.log('用户点击取消');
					}
				}
			});
		} else {
			// uni.setStorageSync('dialing', true)
			// dialingBool.value = true
			asyncSaveOpenNew()
			// onMessages()
		}
	}
	// 关闭连接
	// onBeforeUnmount(() => {
	// 	close()
	// })
</script>

<style lang="scss" scoped>
	.infossf {
		padding: 30rpx;
		background: red;
		color: #ffffff;
		text-align: center;
	}

	.Home {
		min-height: 100vh;
		background: #f6f7fa;

		.introduce {
			position: relative;
			z-index: 9;

			.backs,
			.content {
				width: 100%;
				height: 580rpx;
			}

			.content {
				padding-top: 120rpx;
				text-align: center;

				.logo {
					width: 160rpx;
					height: 160rpx;
					margin-bottom: 26rpx;
				}

				.title {
					font-size: 56rpx;
					margin-bottom: 14rpx;
				}

				.deacs {
					font-size: 28rpx;
					opacity: 0.8;
				}
			}
		}

		.information {
			position: relative;
			z-index: 10;
			margin-top: -80rpx;
			background: #f6f7fa;
			overflow: hidden;
			padding: 0 24rpx;
			box-sizing: border-box;
			border-radius: 40rpx;

			.person {
				padding: 48rpx 0;
				position: relative;
				display: grid;
				grid-template-columns: 100rpx 1fr;
				grid-column-gap: 24rpx;

				.person-img {
					width: 100rpx;
					height: 100rpx;
				}

				.desc {
					opacity: 0.6;
					margin-top: 10rpx;
				}

				.selected {
					right: 0;
					top: 50%;
					margin-top: -26rpx;
					display: flex;
					width: 160rpx;
					height: 52rpx;
					justify-content: center;
					align-items: center;
					border-radius: 100rpx;
					background: rgba(97, 211, 0, 0.2);
					color: #61d300;

					.backs {
						background: #61d300;
					}
				}

				.drop {
					width: 12rpx;
					height: 12rpx;
					border-radius: 100rpx;
					margin-right: 14rpx;
				}


				.selecteds {
					background: rgba(153, 153, 153, .6);
					color: #f6f6f6;

					.backs {
						background: #f6f6f6;
					}
				}
			}

			// 自动拨号
			.calling {
				background: #ffffff;
				padding: 30rpx 40rpx;
				display: grid;
				grid-template-columns: 76rpx 1fr;
				grid-column-gap: 20rpx;
				border-radius: 20rpx;

				.outbound {
					width: 74rpx;
					height: 76rpx;
					background: #FF9600;
					border-radius: 20rpx;
					display: flex;
					justify-content: center;
					align-items: center;

					.outbound-icons {
						width: 40rpx;
						height: 40rpx;
					}
				}

				.icons {
					width: 76rpx;
					height: 76rpx;
				}

				.switch {
					width: 100%;
					display: flex;
					align-items: center;
					justify-content: space-between;
				}

				.switch-button {
					margin: 0;
					width: 140rpx;
					height: 60rpx;
					padding: 0;
					color: #ffffff;
					border-radius: 100rpx;
				}

				.switch-button::after {
					border: 0;
				}

				.cribe {
					line-height: 36rpx;
					opacity: 0.5;
					margin-top: 10rpx;
				}
			}

			.steps {
				display: flex;
				justify-content: space-between;
				padding: 40rpx 36rpx;
				border-radius: 20rpx;
				margin-top: 32rpx;

				.step {
					width: 50rpx;
					height: 50rpx;
					margin: 0 auto;
					border-radius: 100rpx;
					margin-bottom: 20rpx;
				}

				.strip {
					width: 140rpx;
					height: 4rpx;
					background: #d8d8d8;
					border-radius: 100rpx;
					margin-top: 23rpx;
				}
			}

			.explanation {
				opacity: 0.6;
				margin-top: 28rpx;
				line-height: 60rpx;
			}

			.log-out {
				padding: 80rpx 0 60rpx;

				:deep(.u-button) {
					border: 0;
					background: #ffffff;
					color: #00154c;
					font-size: 30rpx;
					height: 100rpx;
					border-radius: 10rpx;
				}
			}
		}
	}
</style>